﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace DBService
{
	public partial class DlgSetRight : System.Windows.Forms.Form
	{
		public DlgSetRight(string group)
		{
			this.mGroup = group;
			this.InitializeComponent();
		}

		private void DlgSetRight_Load(object sender, EventArgs e)
		{
			foreach (DbRole item in DbRole.GetAllRoles(BimServerDB.Default, this.mGroup))
			{
				this.cbxRoles.Items.Add(item);
			}
			if (this.cbxRoles.Items.Count > 0)
			{
				this.cbxRoles.SelectedIndex = 0;
			}
		}

		private void cbxRoles_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.dgvRights.Rows.Clear();
			if (this.cbxRoles.SelectedItem != null)
			{
				try
				{
					List<DbRight> rights = ((DbRole)this.cbxRoles.SelectedItem).GetRights();
					foreach (DbRight dbRight in DbRight.GetAllRights(BimServerDB.Default, this.mGroup))
					{
						if (rights.Contains(dbRight))
						{
							this.dgvRights.Rows.Add(new object[]
							{
								true,
								dbRight.Name,
								dbRight.Description,
								dbRight.Id
							});
						}
						else
						{
							this.dgvRights.Rows.Add(new object[]
							{
								false,
								dbRight.Name,
								dbRight.Description,
								dbRight.Id
							});
						}
					}
					foreach (object obj in ((IEnumerable)this.dgvRights.Rows))
					{
						DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
						if (dataGridViewRow.Cells[1].Value.ToString() == "系统管理")
						{
							dataGridViewRow.ReadOnly = true;
							dataGridViewRow.DefaultCellStyle.BackColor = Color.Gray;
						}
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}
		}

		private void btnCancle_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			if (this.cbxRoles.SelectedItem != null)
			{
				try
				{
					DbRole dbRole = (DbRole)this.cbxRoles.SelectedItem;
					List<DbRight> list = new List<DbRight>();
					foreach (object obj in ((IEnumerable)this.dgvRights.Rows))
					{
						DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
						if ((bool)dataGridViewRow.Cells["add"].Value)
						{
							list.Add(new DbRight(Convert.ToInt32(dataGridViewRow.Cells["rGUID"].Value), dataGridViewRow.Cells["rName"].Value.ToString(), dataGridViewRow.Cells["rDesc"].Value.ToString(), dbRole.Database));
						}
					}
					dbRole.UpdateRights(list);
					MessageBox.Show("更新成功。");
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}
		}

		private string mGroup = "";
	}
}
